<template>
    <div class="container">
        <div class="main">
            <div class="header">
                <el-button type="primary" @click="add">新建</el-button>
                <el-button type="success" @click="importData">导入</el-button>
                <el-button type="warning" @click="edit">编辑</el-button>
            </div>
            <el-table :data="tableData" border class="eltable">
                <el-table-column prop="cprk_zt" label="状态" width="80">
                    <template #default="{ row }">
                        <span v-if="row.cprk_zt === 1">未入库</span>
                        <span v-else-if="row.cprk_zt === 2">已入库</span>
                    </template>
                </el-table-column>
                <el-table-column prop="cprk_code" label="入库单号"></el-table-column>
                <el-table-column prop="cprk_lx" label="入库类型"></el-table-column>
                <el-table-column prop="cprk_gdh" label="生产工单号"></el-table-column>
                <el-table-column prop="cprk_bz" label="备注"></el-table-column>
                <el-table-column prop="user1_name" label="创建人"></el-table-column>
                <el-table-column prop="create_time" label="创建时间">
                    <template #default="{ row }">
                        {{ formatDate(row.create_time) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                    <template #default="{ row }">
                        <el-button type="text" @click="xxRow(row)">详细</el-button>
                        <el-button type="text" @click="rkRow(row)" :disabled="row.cprk_zt === 2">入库作业</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize"
                :total="totalItems" layout="total, prev, pager, next, jumper">
            </el-pagination>
        </div>
    </div>

    <el-dialog v-model="dialogVisible" title="增加" height="800">
        <el-form :model="form" :inline="true" class="demo-form-inline">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="领料出库单号">
                        <el-input v-model="form.cprk_code" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="出库类型">
                        <el-input v-model="form.cprk_lx" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="生产工单号">
                        <el-select v-model="form.cprk_gdh" placeholder="请选择工单号" clearable style="width: 200px;">
                            <el-option v-for="item in workOrderOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="备注">
                        <el-input v-model="form.cprk_bz"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-button type="primary" @click="addwl" style="float: right;">+添加成品</el-button>
        <el-table :data="xxtableData" border style="font-size: 80%;">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="cp_code" label="成品编码"></el-table-column>
            <el-table-column prop="cprkxx_cpmc" label="成品名称"></el-table-column>
            <el-table-column prop="cprkxx_cpfl" label="成品分类"></el-table-column>
            <el-table-column prop="cprkxx_cpdw" label="成品单位"></el-table-column>
            <el-table-column prop="cprkxx_rksl" label="出库数量">
                <template #default="{ row }">
                    <el-input v-model="row.cprkxx_rksl" placeholder="请输入" type="number" min="0"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row, $index }">
                    <el-button type="text" size="mini" @click="deleteRow($index)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addqr">确 定</el-button>
        </span>
    </el-dialog>

    <el-dialog v-model="materialDialogVisible" title="选择物料" width="80%">
        <el-table ref="materialTable" :data="materialList" @selection-change="handleMaterialSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="成品编码" prop="cp_code" />
            <el-table-column label="成品名称" prop="cp_name" />
            <el-table-column label="成品分类" prop="cp_flname" />
            <el-table-column label="成品单位" prop="dw_name" />
        </el-table>

        <!-- 模态框底部按钮 -->
        <template #footer>
            <el-button @click="materialDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmMaterialSelection">确定</el-button>
        </template>
    </el-dialog>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {
    setup() {
        const userId = localStorage.getItem('userId');
        const router = useRouter();
        const searchKey = ref('');
        const treeData = ref([]);
        const xxtableData = ref([]);
        const dialogVisible = ref(false);
        const materialDialogVisible = ref(false);
        const materialList = ref([]); // 确保初始化为数组
        const materialTable = ref(null); // 确保初始化为 null
        const selectedMaterials = ref([]); // 选中的物料
        const form = ref({
            cprk_code: '',
            cprk_lx: '',
            cprk_gdh: '',
            cprk_bz: '',
        });
        const workOrderOptions = ref([]);
        const defaultProps = {
            children: 'children',
            label: 'label',
        };
        // 格式化日期函数
        const formatDate = (dateString) => {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
        };
        const tableData = ref([]);
        const selectedFilter = ref('');
        const searchTable = ref('');
        const currentPage = ref(1);
        const pageSize = ref(10);

        const totalItems = ref(3);
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并补零
        const day = String(now.getDate()).padStart(2, '0'); // 补零

        // 生成四位随机数
        const randomNumber = Math.floor(1000 + Math.random() * 9000); // 生成1000到9999之间的随机数

        // 拼接时间字符串和随机数
        const formattedTime = `${year}${month}${day}`;
        let id = `cpck${formattedTime}${randomNumber}`
        const setDefaultValue = () => {
            form.value.cprk_code = id; // 随机单号示例
            form.value.cprk_lx = '成品入库'; // 固定类型示例
            form.value.cprk_gdh = '';
            form.value.cprk_bz = '';
        }
        const deleteRow = (index) => {
            xxtableData.value.splice(index, 1);
        };

        const sx = () => {
            axios
                .get(
                    '/api/WMS_CCPRK/GetCCPRK?PageNumber=' + currentPage.value + '&pageSize=' + pageSize.value
                )
                .then((response) => {
                    console.log(response.data);
                    tableData.value = response.data.wMS_CCPRKs || [];
                    totalItems.value = response.data.zon || 0;
                })
                .catch((error) => {
                    console.error('错误:', error);
                });
        };
        const openMaterialDialog = async () => {
            const response = await axios.get('/api/Mes_gdrw/GetMes_gdrw');
            console.log(response.data);
            workOrderOptions.value = response.data.map(item => ({
                label: item.gdrw_code, // 假设返回的数据中仓库名称字段为 name
                value: item.gdrw_code    // 假设返回的数据中仓库 ID 字段为 id
            }));
        };

        const addwl = () => {
            axios.get('api/BD_CP/GetBD_CP').then((response) => {
                console.log(response.data);
                materialList.value = response.data || [];
            });
            materialDialogVisible.value = true;
        };

        const addqr = async () => {
            // 确认逻辑
            try {
                console.log('from', form.value);
                console.log('xx', xxtableData.value);

                // 第一个请求
                const rkResponse = await axios.post('/api/WMS_CCPRK/AddCCPRK', {
                    cprk_code: form.value.cprk_code,
                    cprk_lx: form.value.cprk_lx,
                    cprk_gdh: form.value.cprk_gdh,
                    cprk_bz: form.value.cprk_bz,
                    create_by: userId,
                });
                console.log('AddCCPRK response:', rkResponse);

                // 第二个请求，处理 xxtableData 中的每一项
                const xxPromises = xxtableData.value.map(async (item) => {
                    console.log(' row:', item);
                    console.log(form.value.cprk_code);
                    return axios.post('/api/WMS_CCPRKXX/AddCCPRKXX', {
                        cp_code: item.cp_code,
                        cprkxx_cpmc: item.cprkxx_cpmc,
                        cprkxx_cpfl: item.cpfl,
                        cprkxx_cpdw: item.cpdw,
                        cprkxx_rksl: item.cprkxx_rksl,
                        cprk_code: form.value.cprk_code,
                    });
                });

                // 等待所有 xxtableData 的请求完成
                const xxResponses = await Promise.all(xxPromises);
                console.log('AddCCPRKXX responses:', xxResponses);

                // 如果所有请求都成功，提示成功
                ElMessage.success('添加成功');
                // 关闭对话框
                dialogVisible.value = false;
                // 刷新表格数据
                sx();
            } catch (error) {
                console.error('Error:', error);
                ElMessage.error('添加失败，请检查输入信息');
            }

        };

        const add = () => {
            dialogVisible.value = true;
            setDefaultValue();
            xxtableData.value = [];
        };

        const edit = () => {
            // 编辑逻辑
        };

        const importData = () => {
            // 导入逻辑
        };

        const query = () => {
            console.log('Querying with:', searchTable.value);
        };

        const xxRow = (row) => {
            console.log('Editing row:', row);
            // router.push({
            //     path: '/FinishedproductXX',
            //     query: { row: JSON.stringify(row) } // 将 row 序列化为 JSON 字符串
            // });
            router.push({
                name: 'FinishedproductXX',
                query: {
                    cprk_code: row.cprk_code
                }
            });
        };

        const rkRow = (row) => {
            console.log('Deleting row:', row);
            router.push({
                path: '/RKFinishedproduct',
                query: { row: JSON.stringify(row) } // 将 row 序列化为 JSON 字符串
            });
        };

        const handleCurrentChange = (page) => {
            currentPage.value = page;
            sx();
        };

        const handleMaterialSelectionChange = (selection) => {
            console.log('Selected materials:', selection);
            selectedMaterials.value = selection;
        };

        const confirmMaterialSelection = async () => {
            if (selectedMaterials.value.length > 0) {
                selectedMaterials.value.forEach((material) => {
                    // 检查物料是否已经存在
                    const isMaterialExist = xxtableData.value.some(
                        (item) => item.cp_code === material.cp_code
                    );
                    console.log(isMaterialExist);
                    console.log('material', material);
                    // 如果物料不存在，则添加到表格顶部
                    if (!isMaterialExist) {
                        xxtableData.value.unshift({
                            cp_code: material.cp_code,
                            cprkxx_cpmc: material.cp_name,
                            cprkxx_cpfl: material.cp_flname,
                            cprkxx_cpdw: material.dw_name,
                            cprkxx_rksl: 0, // 初始值为 0
                            cpfl: material.cp_fl,
                            cpdw: material.dw_code,
                        });

                    }
                });
            }
            materialDialogVisible.value = false;
        };

        onMounted(() => {
            sx();
            openMaterialDialog();
        });

        return {
            searchKey,
            treeData,
            defaultProps,
            tableData,
            selectedFilter,
            searchTable,
            currentPage,
            pageSize,
            totalItems,
            add,
            edit,
            importData,
            query,
            xxRow,
            rkRow,
            handleCurrentChange,
            dialogVisible,
            form,
            workOrderOptions,
            xxtableData,
            addwl,
            addqr,
            deleteRow,
            materialDialogVisible,
            materialList,
            materialTable,
            handleMaterialSelectionChange,
            confirmMaterialSelection,
            setDefaultValue,
            formatDate
        };
    },
};
</script>

<style>
.container {
    display: flex;
    gap: 20px;
    height: 95%;
}

.sidebar {
    height: 100%;
}

.main {
    width: 80%;
    flex: 1;
    height: 100%;
}

.header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 20px;
}

.eltable {
    height: 95%;
}

.letree {
    height: 100%;
}
</style>